package com.fishV.BI.MQ;

import com.fishV.BI.common.ErrorCode;
import com.fishV.BI.constant.RabbitMQConstant;
import com.fishV.BI.exception.ThrowUtils;
import com.fishV.BI.model.entity.Chart;
import com.fishV.BI.service.ChartService;
import com.fishV.BI.utils.AIUtils;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static org.springframework.amqp.support.AmqpHeaders.DELIVERY_TAG;

/**
 * @author yuwei
 * @date 11:14 2024/10/20
 */
@Component
public class RabbitMqConsumer {
    @Resource
    private ChartService chartService;
    @Resource
    private AIUtils aiUtils;
    @SneakyThrows
    @RabbitListener(queues = RabbitMQConstant.QUEUE_NAME,ackMode = "MANUAL")
    public void receiveMessage(Chart chart, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)  long tag){
        chart.setStatus("running");
        chart.setExecMessage("正在分析中，请稍后");
        Boolean res1 = chartService.updateById(chart);
        if(!res1){
            handleException(chart,"启动失败");
            return;
        }
        StringBuilder userInput = new StringBuilder();
        String goal = chart.getGoal();
        String type = chart.getChartType();
        userInput.append("分析目标：");
            goal = goal + "，图表类型为：" + type;
        userInput.append(goal);
        userInput.append("\n");
        userInput.append("数据：");
        userInput.append(chart.getChartData());

        String response = aiUtils.getAiResult(true, userInput.toString());
        String[] result = response.split("result:");
        if(result.length < 3){
            handleException(chart,"AI分析失败");
            return ;
        }
        chart.setGenChart(result[1].trim());
        chart.setStatus("success");
        chart.setExecMessage("分析成功");
        chart.setGenResult(result[2].trim());
        Boolean res2 = chartService.updateById(chart);
        if(!res2){
            handleException(chart,"AI分析失败");
            return;
        }
        channel.basicAck(tag,false);
    }


    public void handleException(Chart chart,String message){
        chart.setStatus("failed");
        chart.setExecMessage(message);
        chartService.updateById(chart);
    }


}
